<template>
  <div class="wrapper">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        effect="dark"
        :closable="false"
      ></el-alert>
      <div class="margin-top-bottom">
        <span>选择商品的分类：</span>
        <el-cascader
          v-model="selectData"
          :options="selectList"
          @change="handleChange"
          :props="defaultClass"
        ></el-cascader>
      </div>
      <el-tabs
        v-model="activeName"
        @tab-click="handleClick"
        type="card"
      >
        <el-tab-pane
          label="用户管理"
          name="many"
        >
          <el-button
            type="primary"
            @click="addClick"
            :disabled="isCanClick"
          >添加参数</el-button>
          <el-table
            :data="paramsList"
            style="width: 100%"
            border
            stripe
          >
            <el-table-column
              label="more"
              width="100"
              type="expand"
            >
              <template slot-scope="scope">
                <el-tag
                  size="medium"
                  closable
                  class="margin-right"
                  @close="handleRemove(scope.row,i)"
                  v-for="(bq,i) in scope.row.attr_vals"
                  :key="i"
                > {{bq}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>

              </template>
            </el-table-column>
            <el-table-column
              label="#"
              width="100"
              type="index"
            >
            </el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            >
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="onEditOption(scope.row)"
                >修改</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="onDelete(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane
          label="配置管理"
          name="only"
        >
          <el-button
            type="primary"
            @click="addClick"
            :disabled="isCanClick"
          >配置管理</el-button>
          <el-table
            :data="paramsList"
            style="width: 100%"
            border
            stripe
          >
            <el-table-column
              label="more"
              width="100"
              type="expand"
            >
              <template slot-scope="scope">
                <el-tag
                  size="medium"
                  closable
                  class="margin-right"
                  @close="handleRemove(scope.row,i)"
                  v-for="(bq,i) in scope.row.attr_vals"
                  :key="i"
                > {{bq}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>

              </template>
            </el-table-column>
            <el-table-column
              label="#"
              width="100"
              type="index"
            >
            </el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            >
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="onEditOption(scope.row)"
                >修改</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="onDelete(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogAddVisible"
      width="50%"
      :close-on-click-modal="false"
      @close="onCancle()"
    >
      <el-form
        :model="addParams"
        :rules="rules"
        label-width="100px"
        ref="addForm"
      >
        <el-form-item
          :label="labelName"
          prop="attr_name"
        >
          <el-input
            v-model="addParams.attr_name"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogAddVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="onCommit"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      activeName: 'many',
      selectData: '',
      selectList: [],
      paramsList: [],
      dialogTitle: '添加动态参数',
      labelName: '添加参数',
      dialogAddVisible: false,
      isCanClick: true,
      isEdit: false,
      addParams: {
        attr_name: '',
        attr_sel: ''
      },
      editParamsObj: {
        attr_name: '',
        catId: 0,
        attrId: 0
      },
      defaultClass: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      rules: {
        attr_name: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    getCatId () {
      return this.selectData[2];
    }
  },
  created () {
    this.getCateGoriesList();
  },
  methods: {
    async getCateGoriesList () {
      const { data: res } = await this.$http.get('categories');
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.selectList = res.data;
    },
    async getGoodsMsgList () {
      const { data: res } = await this.$http.get(`categories/${this.getCatId}/attributes`, { params: { sel: this.activeName } });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      res.data.forEach(element => {
        element.inputVisible = false;
        element.inputValue = '';
        element.attr_vals = element.attr_vals.length === 0 ? [] : element.attr_vals.split(',');
      });
      this.paramsList = res.data;
    },
    async addParamsData () {
      this.addParams.attr_sel = this.activeName;
      const { data: res } = await this.$http.post(`categories/${this.getCatId}/attributes`, this.addParams);
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getGoodsMsgList();
    },
    async editParamsData () {
      this.addParams.attr_sel = this.activeName;
      const { data: res } = await this.$http.post(`categories/${this.getCatId}/attributes`, this.addParams);
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getGoodsMsgList();
    },
    async deleteParams (data) {
      const { data: res } = await this.$http.delete(`categories/${data.cat_id}/attributes/${data.attr_id}`);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getGoodsMsgList();
    },
    async addOrRemoveTagNameOrEidtName (data) {
      let editParams = '';
      let catId = '';
      let attrId = '';
      if (this.isEdit) {
        editParams = { attr_name: this.addParams.attr_name, attr_sel: this.activeName };
        catId = this.editParamsObj.catId;
        attrId = this.editParamsObj.attrId;
      } else {
        editParams = { attr_name: data.attr_name, attr_sel: this.activeName, attr_vals: data.attr_vals.join(',') };
        catId = data.cat_id;
        attrId = data.attr_id;
      }
      const { data: res } = await this.$http.put(`categories/${catId}/attributes/${attrId}`,
        editParams);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      if (this.isEdit) {
        this.getGoodsMsgList();
        this.isEdit = false;
      }
    },
    handleChange () {
      if (this.selectData.length !== 3) {
        this.selectData = [];
        this.paramsList = [];
        this.isCanClick = true;
        return false;
      }
      this.isCanClick = false;
      this.getGoodsMsgList();
    },
    handleClick () {
      this.handleChange();
    },
    onDelete (data) {
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteParams(data)
      });
    },
    onEditOption (data) {
      this.dialogAddVisible = true;
      this.isEdit = true;
      this.addParams.attr_name = data.attr_name;
      this.editParamsObj.catId = data.cat_id;
      this.editParamsObj.attrId = data.attr_id;
      if (this.activeName === 'many') {
        this.dialogTitle = '修改动态参数';
        this.labelName = '动态参数';
      } else {
        this.dialogTitle = '修改静态属性';
        this.labelName = '静态属性';
      }
    },
    onCommit () {
      this.$refs.addForm.validate(async (result) => {
        if (!result) return;
        this.dialogAddVisible = false;
        if (this.isEdit) {
          this.addOrRemoveTagNameOrEidtName('');
        } else {
          this.addParamsData();
        }
      });
    },
    onCancle () {
      this.$refs.addForm.clearValidate();
      this.$refs.addForm.validate((result) => {
      });
      this.$refs.addForm.clearValidate();
    },
    addClick () {
      this.dialogAddVisible = true;
      this.isEdit = false;
      this.addParams.attr_name = '';
      if (this.activeName === 'many') {
        this.dialogTitle = '添加动态参数';
        this.labelName = '添加参数';
      } else {
        this.dialogTitle = '添加静态属性';
        this.labelName = '静态属性';
      }
    },
    showInput (data) {
      data.inputVisible = true;
      data.inputValue = '';
      // 输入框聚焦
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm (data) {
      data.inputVisible = false;
      const newValue = data.inputValue.trim();
      if (newValue.length !== 0) {
        data.attr_vals.push(newValue)
        this.addOrRemoveTagNameOrEidtName(data);
      }
    },
    handleRemove (data, i) {
      data.attr_vals.splice(i, 1);
      this.addOrRemoveTagNameOrEidtName(data);
    }
  }
}
</script>
<style lang="scss" scoped>
.margin-top-bottom {
  margin: 20px 0;
}
.margin-right {
  margin-right: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
